<template>
  <div class="fullscreen-container">
    <div class="content-wrapper">
      <el-card style="width: 100%;">
        <template #header>
          <div class="card-header">
            <span>我的考试</span>
          </div>
        </template>
        
        <!-- 状态筛选按钮 -->
        <div class="status-filter">
          <el-button 
            :type="filterStatus === 'all' ? 'primary' : 'default'" 
            @click="filterStatus = 'all'"
          >
            全部考试
          </el-button>
          <el-button 
            :type="filterStatus === '进行中' ? 'primary' : 'default'" 
            @click="filterStatus = '进行中'"
          >
            进行中
          </el-button>
          <el-button 
            :type="filterStatus === '未开始' ? 'primary' : 'default'" 
            @click="filterStatus = '未开始'"
          >
            未开始
          </el-button>
          <el-button 
            :type="filterStatus === '已过期' ? 'primary' : 'default'" 
            @click="filterStatus = '已过期'"
          >
            已过期
          </el-button>
        </div>
        
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-input v-model="searchQuery" placeholder="请输入考试名称" prefix-icon="Search" style="width: 400px;" />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
        
        <!-- 考试表格 -->
        <el-table :data="filteredExams" style="width: 100%">
          <el-table-column prop="examId" label="考试ID" width="80"></el-table-column>
          <el-table-column prop="examName" label="考试名称"></el-table-column>
          <el-table-column prop="courseName" label="所属课程" width="120"></el-table-column>
          <el-table-column prop="totalScore" label="总分" width="80"></el-table-column>
          <el-table-column prop="duration" label="考试时长(分钟)" width="150"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag v-if="row.statusValue === 0" type="info">未开始</el-tag>
              <el-tag v-else-if="row.statusValue === 1" type="success">进行中</el-tag>
              <el-tag v-else-if="row.statusValue === 2" type="warning">已结束</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button 
                v-if="row.statusValue === 1" 
                type="primary" 
                size="small" 
                @click="handleTakeExam(row)"
              >
                进入考试
              </el-button>
              <el-button 
                v-else-if="row.statusValue === 0" 
                type="info" 
                size="small" 
                @click="handleViewExam(row)"
              >
                查看详情
              </el-button>
              <el-button 
                v-else 
                type="warning" 
                size="small" 
                @click="handleViewResults(row)"
              >
                查看结果
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
  
  <!-- 考试详情对话框 -->
  <el-dialog v-model="examDetailDialogVisible" :title="selectedExam?.examName" width="600px">
    <div v-if="selectedExam">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="考试名称">{{ selectedExam.examName }}</el-descriptions-item>
        <el-descriptions-item label="所属课程">{{ selectedExam.courseName }}</el-descriptions-item>
        <el-descriptions-item label="总分">{{ selectedExam.totalScore }}</el-descriptions-item>
        <el-descriptions-item label="考试时长">{{ selectedExam.duration }}分钟</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ selectedExam.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ selectedExam.endTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="selectedExam && selectedExam.statusValue === 0" type="info">未开始</el-tag>
          <el-tag v-else-if="selectedExam && selectedExam.statusValue === 1" type="success">进行中</el-tag>
          <el-tag v-else-if="selectedExam && selectedExam.statusValue === 2" type="warning">已结束</el-tag>
          <el-tag v-else-if="selectedExam && selectedExam.statusValue === 3" type="primary">已提交</el-tag>
          <el-tag v-else-if="selectedExam && selectedExam.statusValue === 4" type="danger">已超时未提交</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="考试说明">{{ selectedExam.description || '无' }}</el-descriptions-item>
      </el-descriptions>
      
      <div v-if="selectedExam && selectedExam.statusValue === 0" style="margin-top: 20px; text-align: center;">
        <el-alert title="考试尚未开始，请在开始时间后进入考试" type="info" show-icon />
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="examDetailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="selectedExam && selectedExam.statusValue === 1" 
          type="primary" 
          @click="handleTakeExam(selectedExam)"
        >
          进入考试
        </el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 考试结果对话框 -->
  <el-dialog v-model="examResultDialogVisible" :title="selectedExam?.examName + ' - 考试结果'" width="800px">
    <div v-if="selectedExam">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="考试名称">{{ selectedExam.examName }}</el-descriptions-item>
        <el-descriptions-item label="所属课程">{{ selectedExam.courseName }}</el-descriptions-item>
        <el-descriptions-item label="总分">{{ selectedExam.totalScore }}</el-descriptions-item>
        <el-descriptions-item label="我的得分">
          <span :class="['score-value', { 'score-high': examResult.score >= selectedExam.totalScore * 0.8, 'score-medium': examResult.score >= selectedExam.totalScore * 0.6 && examResult.score < selectedExam.totalScore * 0.8, 'score-low': examResult.score < selectedExam.totalScore * 0.6 }]">
            {{ examResult.score }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ examResult.startTime }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ examResult.submitTime }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 题目详情 -->
      <div style="margin-top: 20px;">
        <h3>题目详情</h3>
        <div v-for="(question, index) in examResult.questions" :key="question.questionId" class="question-item">
          <el-card style="margin-bottom: 15px;">
            <template #header>
              <span>第{{ index + 1 }}题 ({{ question.type }} - {{ question.score }}分)</span>
            </template>
            <div class="question-content">
              <p v-html="question.content"></p>
            </div>
            <div class="question-answer">
              <p><strong>正确答案：</strong>{{ question.correctAnswer }}</p>
              <p><strong>我的答案：</strong>
                <span :class="{ 'answer-incorrect': question.userAnswer !== question.correctAnswer }">
                  {{ question.userAnswer || '未作答' }}
                </span>
              </p>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="examResultDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getStudentExams, type ExamStudentVo } from '@/services/examService'
import { get, post } from '@/utils/api'

const router = useRouter()

// 定义考试结果题目接口
interface ExamResultQuestion {
  questionId: number
  type: string
  content: string
  correctAnswer: string
  userAnswer: string
  score: number
}

// 考试数据
const allExams = ref<any[]>([])
const loading = ref(false)

// 获取学生考试列表
const fetchExams = async () => {
  try {
    loading.value = true
    const response = await getStudentExams()
    if (response.code === 200) {
      // 转换后端数据格式以匹配前端组件
      allExams.value = response.data.map((exam: ExamStudentVo) => ({
        examId: exam.examId,
        examName: exam.examName,
        courseName: exam.courseName,
        totalScore: exam.totalScore,
        duration: exam.examDuration,
        startTime: exam.startTime,
        endTime: exam.endTime,
        status: getStatusText(exam.status),
        description: exam.description,
        statusValue: exam.status // 保存原始状态值用于比较
      }))
    } else {
      ElMessage.error(response.msg || '获取考试列表失败')
    }
  } catch (error) {
    ElMessage.error('获取考试列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已过期'
    case 3: return '已提交'
    case 4: return '已超时未提交'
    default: return '未知'
  }
}

// 筛选状态
const filterStatus = ref('all')
const searchQuery = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = computed(() => {
  let result = allExams.value
  
  // 状态筛选
  if (filterStatus.value !== 'all') {
    // 根据筛选状态转换为对应的statusValue
    let statusValue: number | null = null
    switch (filterStatus.value) {
      case '未开始': statusValue = 0; break
      case '进行中': statusValue = 1; break
      case '已结束': statusValue = 2; break
      case '已提交': statusValue = 3; break
      case '已超时未提交': statusValue = 4; break
    }
    
    if (statusValue !== null) {
      result = result.filter(exam => exam.statusValue === statusValue)
    }
  }
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(exam => 
      exam.examName.toLowerCase().includes(query) || 
      exam.courseName.toLowerCase().includes(query)
    )
  }
  
  return result.length
})

// 对话框相关
const examDetailDialogVisible = ref(false)
const examResultDialogVisible = ref(false)
const selectedExam = ref<any>(null)

// 考试结果数据
const examResult = ref<{
  score: number
  startTime: string
  submitTime: string
  questions: ExamResultQuestion[]
}>({
  score: 0,
  startTime: '',
  submitTime: '',
  questions: []
})

// 筛选后的考试数据
const filteredExams = computed(() => {
  let result = allExams.value
  
  // 状态筛选
  if (filterStatus.value !== 'all') {
    // 根据筛选状态转换为对应的statusValue
    let statusValue: number | null = null
    switch (filterStatus.value) {
      case '未开始': statusValue = 0; break
      case '进行中': statusValue = 1; break
      case '已结束': statusValue = 2; break
      case '已提交': statusValue = 3; break
      case '已超时未提交': statusValue = 4; break
    }
    
    if (statusValue !== null) {
      result = result.filter(exam => exam.statusValue === statusValue)
    }
  }
  
  // 搜索筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(exam => 
      exam.examName.toLowerCase().includes(query) || 
      exam.courseName.toLowerCase().includes(query)
    )
  }
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 在组件挂载时获取考试数据
onMounted(() => {
  fetchExams()
})

// 进入考试
const handleTakeExam = async (row: any) => {
  if (row.statusValue !== 1) { // 1表示进行中
    ElMessage.warning('只有进行中的考试才能进入答题')
    return
  }
  
  ElMessageBox.confirm(`确定要进入《${row.examName}》考试吗？考试时长为${row.duration}分钟。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 发送POST请求到/student-exam/record/enter更新考试状态
      const response = await post('/student-exam/record/enter', { examId: row.examId })
      
      if (response.code === 200) {
        // 跳转到考试答题页面
        router.push(`/student/exam/take/${row.examId}`)
      } else {
        ElMessage.error(response.msg || '进入考试失败')
      }
    } catch (error) {
      ElMessage.error('进入考试失败')
      console.error('进入考试失败:', error)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 查看考试详情
const handleViewExam = (row: any) => {
  selectedExam.value = row
  examDetailDialogVisible.value = true
}

// 查看考试结果
const handleViewResults = async (row: any) => {
  selectedExam.value = row
  
  try {
    // 向/student-exam/query/result发送GET请求，携带examId参数
    const response = await get('/student-exam/query/result', { examId: row.examId })
    
    if (response.code === 200 && response.data) {
      const resultData = response.data
      
      // 将响应数据封装进examResult
      examResult.value = {
        score: resultData.totalScore || 0,
        startTime: resultData.startTime ? resultData.startTime.replace('T', ' ').substring(0, 19) : '',
        submitTime: resultData.endTime ? resultData.endTime.replace('T', ' ').substring(0, 19) : '',
        questions: resultData.questionList ? resultData.questionList.map((q: any) => ({
          questionId: q.questionId,
          type: '单选题', // 根据实际情况可能需要调整
          content: q.questionContent,
          correctAnswer: q.correctAnswer,
          userAnswer: q.yourAnswer || '未作答',
          score: 0 // 根据实际情况可能需要调整
        })) : []
      }
    } else {
      ElMessage.error(response.msg || '获取考试结果失败')
    }
  } catch (error) {
    ElMessage.error('获取考试结果失败')
    console.error('获取考试结果失败:', error)
  }
  
  examResultDialogVisible.value = true
}

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
  ElMessage.info(`搜索：${searchQuery.value}`)
}

// 分页相关函数
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
}
</script>

<style scoped>
.fullscreen-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: #f5f5f5;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  overflow: hidden;
}

.content-wrapper {
  width: 100%;
  height: 100%;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.status-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.score-value {
  font-weight: bold;
  font-size: 18px;
}

.score-high {
  color: #67c23a;
}

.score-medium {
  color: #e6a23c;
}

.score-low {
  color: #f56c6c;
}

.question-item {
  margin-bottom: 15px;
}

.question-content {
  margin-bottom: 15px;
}

.question-answer {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
}

.answer-incorrect {
  color: #f56c6c;
  font-weight: bold;
}
</style>